import { ref, watch, nextTick, computed } from 'vue'
export default function useFixed(props) {
  const TITLE_HEIGHT = 30
  const groupRef = ref(null) // 获取到Dom
  const listHeights = ref([]) // 每个li的高度
  const scrollY = ref(0) // scroll插件滚动到的值
  const currentIndex = ref(0) // 每个li的下标
  const distance = ref(0)//  当前组距离下个组的距离

  const fixedTitle = computed(() => {
    if (scrollY.value < 0) {
      return ''
    }
    const currentGroup = props.data[currentIndex.value] // 获取到当前的li的下标值 对应数据的下标就是li组的标题返回
    // console.log(currentGroup)
    return currentGroup ? currentGroup.title : ''
  })
  const fixedStyle = computed(() => { // 组的底部到达顶部 让元素偏移 动画替换的效果
    const distanceVal = distance.value // 距离顶部的位置
    const diff = (distanceVal > 0 && distanceVal < TITLE_HEIGHT) ? distanceVal - TITLE_HEIGHT : 0
    return {
      transform: `translate3d(0,${diff}px,0)`
    }
  })
  watch(() => props.data, async() => { // 监听数据变化获取Dom高度
    await nextTick()
    calculate()
  })
  watch(scrollY, (newY) => {
    const listHeightsVal = listHeights.value
    for (let i = 0; i < listHeightsVal.length; i++) { // 所有li的每个高度
      const heithtTop = listHeightsVal[i]
      const heightBottom = listHeightsVal[i + 1]
      if (newY > heithtTop && newY <= heightBottom) {
        currentIndex.value = i
        // console.log(heithtTop, heightBottom)
        // 组的最下面位置减去scroll位置 获取到每个组底部距离顶部的位置
        distance.value = heightBottom - newY
      }
    }
  })
  function calculate() { // 获取高度
    const list = groupRef.value.children // 所有li的高度
    const listHeightsVal = listHeights.value // 定义数组存放每个li的高度
    let height = 0
    listHeightsVal.length = 0
    listHeightsVal.push(height)

    for (let i = 0; i < list.length; i++) { // 遍历所有li 获取到每个li的高度 存放到数组中
      height += list[i].clientHeight
      listHeightsVal.push(height)
    }
  }
  function onScroll(pos) {
    scrollY.value = -pos.y
  }
  return {
    groupRef,
    onScroll,
    fixedTitle,
    fixedStyle,
    currentIndex
  }
}
